﻿
//

//


namespace Admin.NET.Core.Service;

public class DefaultFileProvider : ICustomFileProvider, ITransient
{
    public Task DeleteFileAsync(SysFile sysFile)
    {
        var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, sysFile.FilePath ?? "", sysFile.Id + sysFile.Suffix);
        if (File.Exists(filePath)) File.Delete(filePath);
        return Task.CompletedTask;
    }

    public async Task<string> DownloadFileBase64Async(SysFile sysFile)
    {
        var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, sysFile.FilePath);
        if (!Directory.Exists(filePath))
            Directory.CreateDirectory(filePath);

        var realFile = Path.Combine(filePath, $"{sysFile.Id}{sysFile.Suffix}");
        if (!File.Exists(realFile))
        {
            Log.Error($"DownloadFileBase64:文件[{realFile}]不存在");
            throw Oops.Oh($"文件[{sysFile.FilePath}]不存在");
        }
        byte[] fileBytes = await File.ReadAllBytesAsync(realFile);
        return Convert.ToBase64String(fileBytes);
    }

    public Task<FileStreamResult> GetFileStreamResultAsync(SysFile sysFile, string fileName)
    {
        var filePath = Path.Combine(sysFile.FilePath ?? "", sysFile.Id + sysFile.Suffix);
        var path = Path.Combine(App.WebHostEnvironment.WebRootPath, filePath);
        return Task.FromResult(new FileStreamResult(new FileStream(path, FileMode.Open), "application/octet-stream") { FileDownloadName = fileName + sysFile.Suffix });
    }

    public async Task<SysFile> UploadFileAsync(IFormFile file, SysFile newFile, string path, string finalName)
    {
        newFile.Provider = ""; // 本地存储 Provider 显示为空
        var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, path);
        if (!Directory.Exists(filePath))
            Directory.CreateDirectory(filePath);

        var realFile = Path.Combine(filePath, finalName);
        await using (var stream = File.Create(realFile))
        {
            await file.CopyToAsync(stream);
        }

        newFile.Url = $"{newFile.FilePath}/{newFile.Id + newFile.Suffix}";
        return newFile;
    }
}